/* 
 *  <copyright file="RemoveActorOnDeathCmp.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using System.Text;

using SobrietyEngine.Actor;
using SobrietyEngine.Events;
using SobrietyEngine.Guids;
using SobrietyEngine.Common;
using SobrietyEngine.Components.Attach;

namespace SobrietyEngine.Components.OnDeath
{
    public class RemoveActor: OnDeathBase, SobrietyEngine.Components.IComponent
    {
        protected CGuid owningActor;

        public RemoveActor():base()
        {
        }

        public override Boolean InitComponent()
        {
            base.InitComponent();

            owningActor = ParentActor.Guid;

            AttachedToActor attachedTo = (AttachedToActor)ParentActor.Query(typeof(AttachedToActor));
            while (attachedTo != null)
            {
                owningActor = attachedTo.AttachedTo.Guid;
                attachedTo = (AttachedToActor)attachedTo.AttachedTo.Query(typeof(AttachedToActor));
            }

            return true;
        }

        override public void HandleEvent(Event e)
        {
            if (e.Type == typeof(Events.Actor.ActorDied))
            {
                Events.Actor.ActorDied ade = (Events.Actor.ActorDied)e.Data;
                if (ade.ActorGuid.Value == this.ParentActor.Guid.Value || ade.ActorGuid.Value == owningActor.Value)
                {
                    ParentActor.MarkedForRemoval = true;
                }                
            }
        }
    }
}